package com.share.netty.simple;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.Date;
import java.util.Scanner;

/**
 * @author caifan
 * @createTime 2020/5/3
 * @desc:
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    /**
     * 客户端连接服务器完成触发该方法
     * @param ctx
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        //从键盘读取数据
        while (true) {
            Scanner scanner = new Scanner(System.in);
//            ByteBuf buf = Unpooled.copiedBuffer(scanner.next(), CharsetUtil.UTF_8);
            ByteBuf buf = ctx.alloc().buffer();
            buf.writeBytes(scanner.next().getBytes(CharsetUtil.UTF_8));
            ctx.writeAndFlush(buf);
        }
        /*int i = 0;
        while (i < 1000) {
            System.out.println(new Date() + "：客户端数据,netty从入门到放弃,java从入门到精通" );
            ByteBuf byteBuf = ctx.alloc().buffer();
            byteBuf.writeBytes("客户端数据,netty从入门到放弃,java从入门到精通".getBytes(CharsetUtil.UTF_8));
            ctx.writeAndFlush(byteBuf);
            i++;
        }*/
    }

    /**
     * 通道读取事件触发，服务器发送数据给客户端
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("收到服务端消息：" + buf.toString(CharsetUtil.UTF_8));
        System.out.println("服务端地址：" + ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
